<?php


namespace App\Admin\Services;

use App\Model\Good;
use App\Model\Stock;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class StockService
{

    /**
     * @desc 获取进出记录
     *
     * @param array $columns
     * @param array $order
     * @param int $pageSize
     * @param int $offset
     *
     * @return array
     *
     * @author: 梅杰[meijie3169@dingtalk.com] at 2020-03-18 16:00:26
     */
    public function getRecordsList(array $columns, array $order, int $pageSize = 10, int $offset = 0)
    {
        $select = [
            DB::raw("stock.*"),
            'goods_img_url',
            'stock',
            'casku',
            'jpsku',
            'uksku',
            'amazon_goods.asin',
            'amazon_goods.sku',
            'amazon_goods.fnsku'
        ];

        $builder = Stock::query()
            ->Join('goods', 'goods_id', '=', 'goods.id')
            ->leftJoin("amazon_goods", 'amazon_goods.id', '=', 'amazon_goods_id');


        foreach ($columns as &$column) {
            if (empty($column['name']) || !isset($column['search']['value'])) {
                continue;
            }
            switch ($column['name']) {
                case 'id':
                    $column['name'] = "stock.id";
                    break;
                default:

            }
            $builder->where($column['name'], 'like', "%" . escapeLikeStr($column['search']['value']) . "%");
        }

        // 处理排序
        foreach ($order as $k => $value) {
            $field = $columns[$value['column']]['name'];
            $builder->orderBy($field == 'id' ? 'stock.id' : $field, $value['dir']);
        }
        $total = $builder->count();

        $data = $builder->orderByDesc('stock.id')
            ->with('user:id,username')
            ->take($pageSize)
            ->offset($offset)
            ->get($select);

        return [
            'total' => $total,
            'data' => $data
        ];
    }


    /**
     * 导出库存进出记录
     *
     * @param array $record 记录数据
     * @param int $operatorId 操作id
     *
     * @return int 成功条数
     */
    public static function importStockRecord(array $record, $operatorId)
    {
        $inputAsin = array_column($record, 'asin');
        $dbGoods = Good::query()
            ->join('amazon_goods', 'amazon_goods_id', '=', 'amazon_goods.id')
            ->whereIn('asin', $inputAsin)
            ->get([
                'goods.id as goodId',
                'asin'
            ]);

        $insert = $update = [];
        foreach ($record as $item) {
            if ($dbGood = $dbGoods->where('asin', $item['asin'])->first()) {

                // 插入log 记录
                $insert[] = [
                    'goods_id' => $dbGood->goodId,
                    'value' => abs($item['value']),
                    'type' => $item['value'] > 0 ? 1 : 0,
                    'user_user_id' => $operatorId,
                    'create_time' => date('Y-m-d H:i:s')
                ];

                // 更新商品的库存
                $update[] = "($dbGood->goodId,{$item['value']})";
            }
        }

        if ($insert) {
            DB::beginTransaction();
            try {
                // 插入记录
                Stock::query()->insert($insert);
                (new Good())->batchUpdateStock($update);
            } catch (\Exception $exception) {
                Log::info($exception->getMessage());
                DB::rollBack();
                return false;
            }
            DB::commit();
        }
        return count($insert);
    }
}
